﻿using System.Data.Entity;
using System.Linq;
using Nop.Core.Data;
using Nop.Core.Domain.ShowCase;

namespace Nop.Services.ShowCase
{
    public class ShowCaseService:IShowCaseService
    {
        public IRepository<ShowCaseProduct> _showCaseProductRepostiory;
        public IRepository<ShowCaseProductItem> _showCaseProductItemRepostiory;


        public ShowCaseService(IRepository<ShowCaseProduct> showCaseProductRepostiory, IRepository<ShowCaseProductItem> showCaseProductItemRepostiory)
        {
            _showCaseProductRepostiory = showCaseProductRepostiory;
            _showCaseProductItemRepostiory = showCaseProductItemRepostiory;
        }

        public ShowCaseProduct GetShowCaseProduct(int id)
        {
            var query = from p in (_showCaseProductRepostiory.Table as IDbSet<ShowCaseProduct>).Include("Items").Include("Items.Product")
                        where p.Id == id
                        select p;
            return query.SingleOrDefault();
        }

        public ShowCaseSaveResult SaveShowCase(ShowCaseProduct showCaseProduct)
        {
            var result = new ShowCaseSaveResult();

            if(showCaseProduct.Id== 0)
            {
                //create
            }
            else
            {
                //update
                var pquery = from p in (_showCaseProductRepostiory.Table as IDbSet<ShowCaseProduct>).Include("Items.Product")
                        where p.Id == showCaseProduct.Id
                        select p;

                var  product  = pquery.SingleOrDefault();

                if (product == null)
                {
                    result.AddError("ShowCase 不存在");
                    return result;
                }

                product.Title = showCaseProduct.Title;
                if (product.Items != null)
                {
                    product.Items.ToList().ForEach(t => _showCaseProductItemRepostiory.Delete(t));
                }

                product.Items = showCaseProduct.Items;

                _showCaseProductRepostiory.Update(product);


            }

            return result;
        }
    }
}